﻿using MySqlX.XDevAPI.Relational;
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Text;
public enum SqlTable
{
    //用户表
    users,

    //设备
    device,

    //皮肤表
    skins,

    //宠物表
    pets,

    //道具表
    props,

    //支付表
    payment,
    //申请
    applys,
    //对话
    chats,
    //访问
    visits,
    //动态
    moments,
    //评论
    comments
}

public class SqlTableClass
{
    public long id;

    public SqlTableClass()
    {

    }
}

public class UserTable
{
    public int dbId;
    public users user;

    public UserTable(int dbId, users user)
    {
        this.dbId = dbId;
        this.user = user;
    }
}
public class users : SqlTableClass
{
    //public string password = "";
    public string nickname;
    public int max_lv;
    public int coin;
    public int diamond;
    public int home_ad_remain;
    public double last_login_time;
    public double last_offline_time;
    public byte is_robot;
    public int login_day;
    public string obtain_login_bonus_day;
    public int obtain_shared_reward;
    public int free_apply_count;
    public string friends;
    public string likes;
    public string belikes;
    public string myfollows;
    public string followers;

    public byte gender;//true: Man, false: woman
    public string name;
    public int marital_status;
    public int birthYear;
    public int birthMonth;
    public int birthDay;
    public string status;
    public string location_province;
    public string location_city;
    public string hometown_province;
    public string hometown_city;
    public string job;
    public string company;
    public int education;
    public string school;
    public float height;
    public float weight;
    public int income;
    public byte realNameVerify;
    public byte jobVerify;
    public byte eduVerify;
    public string aboutMe;
    public string familyBackground;
    public string interest;
    public string loveView;
    public string idealCompanion;

    public int  requirement_min_age;
    public int  requirement_max_age;
    public int  requirement_min_height;
    public int  requirement_max_height;
    public int  requirement_min_edu;
    public byte requirement_same_location;
    public byte requirement_same_hometown;
    public byte requirement_only_unmarried;

    public users():base()
    {

    }

    
    public static long DeviceId2UserTableId(long id)
    {
        if (id < 0)
        {
            return id;
        }

        long index = (id / ServerConfig.MaxDBUserID);
        return index + 1;
    }
    public static long UserTableId2DeviceId(string databaseName, long userId)
    {
        //if (databaseName == ServerConfig.DBUserRobot)
        //{
        //    return id;
        //}

        string dbIdStr = databaseName.Replace(ServerConfig.DBUserBase, "");
        int.TryParse(dbIdStr, out int dbId);
        return UserTableId2DeviceId(dbId, userId);
        //if (dbId > 0 && dbId <= ServerConfig.MaxDBUserID)
        //{
        //    return (dbId - 1) + (userId - 1) * ServerConfig.MaxDBUserID;
        //}
        //else
        //{
        //    GameDebug.LogError($"invalid user database name:{databaseName}");
        //    return -1;
        //}
    }
    public static long UserTableId2DeviceId(int dbId, long userId)
    {
        if (dbId > 0 && dbId <= ServerConfig.MaxDBUserID)
        {
            return (dbId - 1) + (userId - 1) * ServerConfig.MaxDBUserID;
        }
        else
        {
            GameDebug.LogError($"invalid user dbId:{dbId}");
            return -1;
        }

    }

    public static string GetUserDatabaseWithDeviceId(long id)
    {
        //if (id < 0)
        //{
        //    return ServerConfig.DBUserRobot;
        //}

        int dbId = (int)(id % 10) + 1;
        return GetUserDatabaseWithDbId(dbId);
    }
    public static string GetUserDatabaseWithDbId(int dbId)
    {
        string databaseName = $"{ServerConfig.DBUserBase}{dbId}";

        return databaseName;
    }


    public static int UpdateCurPet(long deviceId,int petId)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "cur_pet", petId.ToString(), "id", userTableId.ToString());
    }
    public static int UpdateDiamond(long deviceId, int diamond)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database,SqlTable.users.ToString(), "diamond", diamond.ToString(), "id", userTableId.ToString());
    }
    public static int UpdateLastLoginTime(long deviceId, double lastLoginTime)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database,SqlTable.users.ToString(), "last_login_time", lastLoginTime.ToString(), "id", userTableId.ToString());
    }
    public static int UpdateLastOfflineTime(long deviceId, double lastOfflineTime)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database,SqlTable.users.ToString(), "last_Offline_time", lastOfflineTime.ToString(),  "id", userTableId.ToString());
    }
    public static int UpdateChargeTime(long deviceId, int chargeTimes)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database,SqlTable.users.ToString(), "charge_count", chargeTimes.ToString(), "id", userTableId.ToString());
    }
    public static int UpdateHomeAdTimesRemain(long deviceId, int remain)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database,SqlTable.users.ToString(), "home_ad_remain", remain.ToString(), "id", userTableId.ToString());
    }
    public static int UpdateNick(long deviceId, string nick)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database,SqlTable.users.ToString(), "nickname", nick, "id", userTableId.ToString());
    }
    public static int UpdateBattleTimes(long deviceId, int battleTimes)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database,SqlTable.users.ToString(), "battle_times", battleTimes.ToString(), "id", userTableId.ToString());
    }
    public static int UpdateWinStage(long deviceId, int stageId)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "stage_level", stageId.ToString(), "id", userTableId.ToString());
    }
    //public static int UpdateUsername(long deviceId, string username,string password)
    //{
    //    string database = users.GetUserDatabaseWithUserId(deviceId);
    //    long userTableId = users.DeviceId2UserTableId(deviceId);

    //    return MysqlFunction.UpdateValues(database, SqlTable.users.ToString(),new string[] { "username" ,"password"},new string[] { username ,password}, new string[] { "id" }, new string[] { userTableId.ToString() });
    //}
    public static int UpdateMaxLv(long deviceId, int newLv)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "max_lv", newLv.ToString(), "id", userTableId.ToString());
    }

    public static int UpdateGetCompensateDate(long deviceId, int compensateDate)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "get_compensate_date", compensateDate.ToString(), "id", userTableId.ToString());
    }

    public static int UpdateLoginDay(long deviceId, int loginDay)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "login_day", loginDay.ToString(), "id", userTableId.ToString());
    }

    public static List<int> ObtainedLoginBonusString2List(string str)
    {
        if(str == null)
        {
            return new List<int>();
        }
        List<int> res = new List<int>();
        for(int i=0;i < str.Length; i++)
        {
            if (str[i].Equals('1'))
            {
                res.Add(i + 1);
            }
        }
        return res;
    }

    static string ObtainedLoginBonusDay2String(List<int> obtainedDay)
    {
        string obtainLoginBonusDay = "";
        for (int i = 1; i <= User.maxObtainLoginBonusDay; i++)
        {
            if (obtainedDay.Contains(i))
            {
                obtainLoginBonusDay += "1";
            }
            else
            {
                obtainLoginBonusDay += "0";
            }
        }
        return obtainLoginBonusDay;
    }
    public static List<long> String2LongList(string str)
    {
        if (string.IsNullOrEmpty(str))
        {
            return new List<long>();
        }
        List<long> longs = new List<long>();
        var res = str.Split('|');
        for (int i = 0; i < res.Length; i++)
        {
            long.TryParse(res[i].Trim(), out long result);
            longs.Add(result);
        }
        return longs;
    }

    public static string LongList2String(List<long> list)
    {
        string res = "";
        for (int i = 0; i < list.Count; i++)
        {
            if (i < list.Count - 1)
                res += list[i] + "|";
            else 
                res += list[i];
        }
        return res;
    }

    public static int UpdateObtainedLoginBonus(long deviceId,  List<int> obtainedDay)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "obtain_login_bonus_day", ObtainedLoginBonusDay2String(obtainedDay), "id", userTableId.ToString());
    }

    public static int UpdateObtainSharedReward(long deviceId, int value)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "obtain_shared_reward", value.ToString(), "id", userTableId.ToString());
    }

    public static users DefaultValue(bool is_robot)
    {
        users user = new users();
        user.nickname = "GUEST";
        user.max_lv = 1;
        user.coin = 0;
        user.diamond = 0;
        user.home_ad_remain = 0;
        //user.last_login_time = last_login_time;
        //user.last_offline_time = last_offline_time;
        user.is_robot = 0;
        user.login_day = 0;
        user.obtain_login_bonus_day = ObtainedLoginBonusDay2String(new List<int> { 1 });
        user.obtain_shared_reward = 0;
        user.gender = 0;
        user.name = "GUEST";
        user.birthYear = 0;
        user.birthMonth = 0;
        user.birthDay = 0;
        user.status = "积极营业";
        user.job = "";
        user.company = "";
        user.education = 0;
        user.school = "";
        user.height = 0;
        user.weight = 0;
        user.income = 0;
        user.aboutMe = "";
        user.familyBackground = "";
        user.interest = "";
        user.loveView = "";
        user.idealCompanion = "";
        user.followers = "";

        user.requirement_min_age = 18;
        user.requirement_max_age = 40;
        user.requirement_min_height = 140;
        user.requirement_max_height = 180;
        user.requirement_min_edu = 0;
        user.requirement_same_location = 0;
        user.requirement_same_hometown = 0;
        user.requirement_only_unmarried = 1;

        return user;
    }

    public static int UpdateBaseInfo(long deviceId, int gender, int birthYear, int education, string locationProv,string locationCity)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string[] keys = new string[] { "gender", "birthYear", "education", "location_province","location_city" };

        string[] values = new string[] { gender.ToString(),birthYear.ToString(), education.ToString(), locationProv, locationCity };

        return MysqlFunction.UpdateValues(database, SqlTable.users.ToString(), keys, values, new string[] { "id" }, new string[] { userTableId.ToString() });
    }
    public static int UpdateDetailInfo(long deviceId, float height, float weight, int maritalStatus, string hometownProvince, string hometownCity, string job)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string[] keys = new string[] { "height", "weight", "marital_status", "hometown_province", "hometown_city", "job" };

        string[] values = new string[] { height.ToString(), weight.ToString(), maritalStatus.ToString(), hometownProvince, hometownCity, job };

        return MysqlFunction.UpdateValues(database, SqlTable.users.ToString(), keys, values, new string[] { "id" }, new string[] { userTableId.ToString() });
    }
    public static int UpdateIntroduction(long deviceId, int type, string content)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string key = "";
        string value = "";
        if (type == IntroductioType.aboutMe)
        {
            key = "aboutMe";
        }
        else if (type == IntroductioType.familyBackground)
        {
            key = "familyBackground";
        }
        else if (type == IntroductioType.interest)
        {
            key = "interest";
        }
        else if (type == IntroductioType.loveView)
        {
            key = "loveView";
        }
        else if (type == IntroductioType.idealCompanion)
        {
            key = "idealCompanion";
        }
        value = content;

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), key, value,  "id" , userTableId.ToString() );
    }

    public static int UpdateFreeApplyCount(long deviceId, int freeApplyCount)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "free_apply_count", freeApplyCount.ToString(), "id", userTableId.ToString());

    }
    public static int UpdateFriends(long deviceId, List<long> friends)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string friendsStr = LongList2String(friends);

        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "friends", friendsStr, "id", userTableId.ToString());
    }
    public static int UpdateLikes(long deviceId, List<long> likes)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string likesStr = LongList2String(likes);
        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "likes", likesStr, "id", userTableId.ToString());
    }
    public static int UpdateBeLikes(long deviceId, List<long> belikes)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string likesStr = LongList2String(belikes);
        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "belikes", likesStr, "id", userTableId.ToString());
    }
    public static int UpdateMyFollows(long deviceId, List<long> follows)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string listStr = LongList2String(follows);
        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "myfollows", listStr, "id", userTableId.ToString());
    }
    public static int UpdateFollowers(long deviceId, List<long> followers)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string followersStr = LongList2String(followers);
        return MysqlFunction.UpdateValue(database, SqlTable.users.ToString(), "followers", followersStr, "id", userTableId.ToString());
    }
    public static int UpdateRequirement(long deviceId, Requirement requirement)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);
        long userTableId = users.DeviceId2UserTableId(deviceId);

        string[] keys = new string[] { "requirement_min_age", "requirement_max_age", "requirement_min_height","requirement_max_height", 
            "requirement_min_edu","requirement_same_location", "requirement_same_hometown","requirement_only_unmarried"};

        int sameLocation = requirement.sameLocation ? 1 : 0;
        int sameHometown = requirement.sameHometown ? 1 : 0;
        int onlyUnmarried = requirement.onlyUnmarried ? 1 : 0;

        string[] values = new string[] { requirement.minAge.ToString(), requirement.maxAge.ToString(), requirement.minHeight.ToString(), requirement.maxHeight.ToString(),
            requirement.minEdu.ToString(),sameLocation.ToString(),sameHometown.ToString(),onlyUnmarried.ToString() };

        return MysqlFunction.UpdateValues(database, SqlTable.users.ToString(), keys, values, new string[] { "id" }, new string[] { userTableId.ToString() });
    }
}


public class device : SqlTableClass
{
    public int login_type;
    public string uuid;
    public string password;
    //public long uid;
    public string lang_type;
    public string os;
    public string device_model;
    public string device_name;

    public device() : base()
    {

    }
    public device( int login_type, string uuid, string lang_type, string os, string device_model, string device_name):base()
    {
        this.login_type = login_type;
        this.uuid = uuid;
        this.lang_type = lang_type;
        this.os = os;
        this.device_model = device_model;
        this.device_name = device_name;
    }

    public static int UpdateUUID(long deviceId, string username, string password)
    {
        return MysqlFunction.UpdateValues(ServerConfig.DBShared, SqlTable.device.ToString(),new string[] { "uuid" ,"password"},new string[] { username ,password}, new string[] { "id" }, new string[] { deviceId.ToString() });
    }


}

public class skins : SqlTableClass
{
    public long uid;
    public int skin_id;

    public skins() : base()
    {

    }

    public skins(long uid, int skin_id) : base()
    {
        this.uid = uid;
        this.skin_id = skin_id;
    }

    public override string ToString()
    {
        return $"[id:{id}  uid:{uid}  skin_id:{skin_id}]";
    }
}

public class pets : SqlTableClass
{
    public long uid;
    public int pet_id;
    public int hp_last_update;
    public double hp_update_time;
    public double wound_time;
    public int mood;
    public int used_skin_index;
    public string property_proportion;
    public int continue_lose_count; 

    public pets() : base()
    {

    }

    public pets( long uid, int pet_id,  int hp_last_update, double hp_update_time,double wound_time, int mood, int used_skin_index, string property_proportion,int continueLoseCount):base()
    {
        this.uid = uid;
        this.pet_id = pet_id;
        this.hp_last_update = hp_last_update;
        this.hp_update_time = hp_update_time;
        this.wound_time = wound_time;
        this.mood = mood;
        this.used_skin_index = used_skin_index;
        this.property_proportion = property_proportion;
        this.continue_lose_count = continueLoseCount;
    }

    public static int UpdateUsedSkinIndex(long deviceId,long id,int index)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.pets.ToString(), "used_skin_index", index.ToString(), "id", id.ToString());
    }
    public static int UpdatePetPower(long deviceId, long id,int power)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.pets.ToString(), "power", power.ToString(),"id", id.ToString());
    }
    public static int UpdatePetMood(long deviceId, long id, int mood)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.pets.ToString(), "mood", mood.ToString(),  "id", id.ToString());
    }
    public static int UpdatePetWound(long deviceId, long id, FixedFloat woundTime)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.pets.ToString(), "wound_time", woundTime.ToString(), "id", id.ToString());
    }
    public static int UpdatePetHp(long deviceId, long id, int hp,double updateTime)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);

        return MysqlFunction.UpdateValues(database, SqlTable.pets.ToString(),new string[] {"hp_last_update", "hp_update_time"},new string[] {hp.ToString(),updateTime.ToString() },new string[] { "id" },new string[]{ id.ToString() });
    }
    public static int UpdatePetsPropertyProportion(long deviceId, long id, int[] propertyArrArr)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.pets.ToString(), "property_proportion", MysqlFunction.IntArray2String(propertyArrArr), "id", id.ToString());
    }
    public static int UpdatePetContinueLoseCount(long deviceId, long id, int count)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);

        return MysqlFunction.UpdateValue(database, SqlTable.pets.ToString(), "continue_lose_count", count.ToString(), "id", id.ToString());
    }
}

public class props : SqlTableClass
{
    public long uid;
    public int prop_id;
    public int num;

    public props():base()
    {

    }

    public props(long uid, int propId, int num) : base()
    {
        this.uid = uid;
        this.prop_id = propId;
        this.num = num;
    }

    public static void SetPropNum(long uid,int propId,int newNum)
    {
        string database = users.GetUserDatabaseWithDeviceId(uid);

        int row = MysqlFunction.UpdateValueMultiWhere(database,SqlTable.props.ToString(), "num", newNum.ToString(), "uid", uid.ToString(), "prop_id", propId.ToString());

        if(row <= 0)
        {
            GameDebug.Log($"插入新行：{propId}");

            props propsTable = new props(uid, propId, newNum);

            MysqlFunction.InsertIntoTable(database,SqlTable.props, propsTable);
        }

        //var reader = MysqlFunction.SelectFromTable(SqlTable.users, "uid", uid.ToString(),"prop_id",propId.ToString());

        //if (reader.HasRows)
        //{
        //    props propsTable = new props();
        //    MysqlFunction.ReadTable(reader, ref propsTable);

        //    int newNum = propsTable.num + addNum;

        //    MysqlFunction.UpdateValue(SqlTable.pets.ToString(), "num", newNum.ToString(), "update_at", CommonFunctions.GetTimeStampSeconds().ToString(), "uid", uid.ToString(),"prop_id",propId.ToString());
        //}
        //else
        //{
        //    props propsTable = new props(uid,propId,addNum);

        //    MysqlFunction.InsertIntoTable(SqlTable.props, propsTable);
        //}
        //reader.Close();
    }
}



public class payment : SqlTableClass
{
    public long uid;
    public string goods_id;
    public string product_id;
    public int pay_type;
    public string transaction_id;
    public string receipt;

    public payment() : base()
    {

    }

    public payment(long uid,string goods_id, string product_id, int pay_type, string transaction_id, string receipt)
    {
        this.uid = uid;
        this.goods_id = goods_id;
        this.product_id = product_id;
        this.pay_type = pay_type;
        this.transaction_id = transaction_id;
        this.receipt = receipt;
    }

    public static bool TransactionExist(long deviceId,string transactionId)
    {
        string database = users.GetUserDatabaseWithDeviceId(deviceId);

        payment exist =  MysqlFunction.FindInTable<payment>(database, SqlTable.payment, "transaction_id", transactionId);
        return exist != null;
    }

}

public class applys : SqlTableClass
{
    public long uid;
    //public int apply_id;
    public long target_user_id;
    public int result;
    public string msg;
    public string reject_msg;
    public long apply_time;
    public long view_time;
    public long result_time;

    public applys() : base()
    {

    }

    public applys(long uid, /*int apply_id,*/ long targetUserId, int result, string msg, string rejectMsg, long applyTime, long viewTime, long resultTime)
    {
        this.uid = uid;
        //this.apply_id = apply_id;
        this.target_user_id = targetUserId;
        this.result = result;
        this.msg = msg;
        this.reject_msg = rejectMsg;
        this.apply_time = applyTime;
        this.view_time = viewTime;
        this.result_time = resultTime;
    }

    public static int SetApply(long userId,long targetUserId, int result, string msg, string rejectMsg, long applyTime, long viewTime, long resultTime)
    {
        string database = users.GetUserDatabaseWithDeviceId(userId);

        GameDebug.Log($"SetApply source:{userId}  target：{targetUserId} ");

        int row = MysqlFunction.UpdateValues(database, SqlTable.applys.ToString(),
            new string[] { "result", "msg", "reject_msg", "apply_time", "view_time", "result_time" },
            new string[] { result.ToString(), msg, rejectMsg, applyTime.ToString(),  viewTime.ToString(), resultTime.ToString() },
            new string[] { "uid", "target_user_id" }, new string[] { userId.ToString(), targetUserId.ToString() });
        
        if (row <= 0)
        {
            GameDebug.Log($"插入新行 targetUserId：{targetUserId}  database:{database}");

            applys table = new applys(userId, targetUserId,  result, msg, rejectMsg, applyTime, viewTime, resultTime);

            long id = MysqlFunction.InsertIntoTable(database, SqlTable.applys, table);
            if (id > 0)
                return 1;
            else
                return -1;
        }
        return row;
    }
}


public class chats : SqlTableClass
{
    public long from_user_id;
    public long target_user_id;
    public string content;
    //public int new_msg_count;

    public chats() : base()
    {

    }

    public chats(long from_user_id, long to_user_id, string content/*, int newMagCount*/)
    {
        this.from_user_id = from_user_id;
        this.target_user_id = to_user_id;
        this.content = content;
        //this.new_msg_count = newMagCount;
    }

    public static int SetChat(long from_user_id, long target_user_id, string content/*, int newMagCount*/)
    {
        string database = users.GetUserDatabaseWithDeviceId(from_user_id);

        GameDebug.Log($"SetDialogue source:{from_user_id}  target：{target_user_id} content:{content}");

        int row = MysqlFunction.UpdateValueMultiWhere(database, SqlTable.chats.ToString(),"content",
            content, "from_user_id", from_user_id.ToString(), "target_user_id", target_user_id.ToString());

        if (row <= 0)
        {
            GameDebug.Log($"插入新行 from_user_id:{from_user_id}  to_user_id：{target_user_id}  database:{database}");

            chats table = new chats(from_user_id, target_user_id, content);

            long id = MysqlFunction.InsertIntoTable(database, SqlTable.chats, table);
            if (id > 0)
                return 1;
            else
                return -1;
        }
        return row;
    }
}

public class visits : SqlTableClass
{
    public long uid;
    public long target_user_id;
    public int total_visit_count;
    public long last_visit_time;

    public visits() : base()
    {

    }

    public visits(long uid, long target_user_id, int total_visit_count, long last_visit_time)
    {
        this.uid = uid;
        this.target_user_id = target_user_id;
        this.total_visit_count = total_visit_count;
        this.last_visit_time = last_visit_time;
    }

    public static int SetVisit(long uid, long target_user_id, int total_visit_count,  long last_visit_time)
    {
        string database = users.GetUserDatabaseWithDeviceId(uid);

        GameDebug.Log($"SetVisit source:{uid}  target：{target_user_id} time:{last_visit_time}");

        int row = MysqlFunction.UpdateValues(database, SqlTable.visits.ToString(),
            new string[] { "total_visit_count", "last_visit_time" },
            new string[] { total_visit_count.ToString(), last_visit_time.ToString() },
            new string[] { "uid", "target_user_id" }, new string[] { uid.ToString(), target_user_id.ToString() });

        if (row <= 0)
        {
            GameDebug.Log($"插入新行 SetVisit targetUserId：{target_user_id}  database:{database}");

            visits table = new visits(uid, target_user_id, total_visit_count, last_visit_time);

            long id = MysqlFunction.InsertIntoTable(database, SqlTable.visits, table);
            if (id > 0)
                return 1;
            else
                return -1;
        }
        return row;
    }
}

public class comments : SqlTableClass
{
    public long moment_user_id;
    public long moment_id;
    public long uid;
    public long time;
    public string content;
    public string likes;
    public string subcomments;

    public comments() : base()
    {

    }

    public comments(long moment_user_id,long moment_id, long uid, long time, string content, string likes, string subcomments)
    {
        this.moment_user_id = moment_user_id;
        this.moment_id = moment_id;
        this.uid = uid;
        this.time = time;
        this.content = content;
        this.likes = likes;
        this.subcomments = subcomments;
    }

    public static int SetSubcomments(long momentUserId,long commentId, string subcomments)
    {
        string database = users.GetUserDatabaseWithDeviceId(momentUserId);

        int row = MysqlFunction.UpdateValues(database, SqlTable.comments.ToString(),
            new string[] {  "subcomments" },
            new string[] {   subcomments },
            new string[] { "id" }, new string[] { commentId.ToString() });

        return row;
    }

    public static long AddComment(long momentUserId, long moment_id, long commentUserId, long time, string content, string likes)
    {
        string database = users.GetUserDatabaseWithDeviceId(momentUserId);

        GameDebug.Log($"插入新行 SetComment moment_id：{moment_id} time：{time} database:{database}");

        comments table = new comments(momentUserId,moment_id, commentUserId, time, content, likes, "");

        long id = MysqlFunction.InsertIntoTable(database, SqlTable.comments, table);
        return id;
    }
    public static int UpdateLikes(long opponent, long commentId, long[] likes)
    {
        string database = users.GetUserDatabaseWithDeviceId(opponent);

        GameDebug.Log($" userId：{opponent} Comment {commentId} 更新likes：{likes.Length} database:{database}");

        int row = MysqlFunction.UpdateValue(database, SqlTable.comments.ToString(), "likes",
         users.LongList2String(likes.AsList()), "id", commentId.ToString());

        return row;
    }
}

public class moments : SqlTableClass
{
    public long uid;
    public long time;
    public string user_location_city;
    public string content;
    public string location;
    public string topic;
    public int moment_status;
    public string likes;
    public string comments;
   // public Tex[] texs;

    public moments() : base()
    {

    }
    public moments(long uid, string user_location_city, long time, string content, string location, string topic, int moment_status, string likes, string comments)
    {
        this.uid = uid;
        this.user_location_city = user_location_city;
        this.time = time;
        this.content = content;
        this.location = location;
        this.topic = topic;
        this.moment_status = moment_status;
        this.likes = likes;
        this.comments = comments;
    }

    public static long AddMoment(long userId, string user_location_city, long time, string content,string location, string topic,int momentStatus, string likes,string comments)
    {
        string database = users.GetUserDatabaseWithDeviceId(userId);

        GameDebug.Log($"插入新行 AddMoment userId：{userId} time：{time} database:{database}");

        moments table = new moments(userId, user_location_city, time, content, location, topic, momentStatus, likes, comments);

        long id = MysqlFunction.InsertIntoTable(database, SqlTable.moments, table);
        return id;
    }

    public static int UpdateLikes(long opponent,long momentId, long[] likes)
    {
        string database = users.GetUserDatabaseWithDeviceId(opponent);

        GameDebug.Log($" userId：{opponent} Moment {momentId} 更新likes：{likes.Length} database:{database}");

        int row = MysqlFunction.UpdateValue(database, SqlTable.moments.ToString(), "likes",
         users.LongList2String(likes.AsList()), "id", momentId.ToString());

        return row;
    }
    public static int UpdateComments(long momentuserId, long momentId, List<long> commentIds)
    {
        string database = users.GetUserDatabaseWithDeviceId(momentuserId);

        GameDebug.Log($" userId：{momentuserId} Moment {momentId} 更新commentIds：{commentIds.Count} database:{database}");

        int row = MysqlFunction.UpdateValue(database, SqlTable.comments.ToString(), "comments",
         users.LongList2String(commentIds), "id", momentId.ToString());

        return row;
    }
}